const { query, transaction } = require('../../../lib/db');
const { authenticateToken } = require('../../../lib/auth');
const { validate, ticketUpdateSchema } = require('../../../lib/validation');
const { logTicketAction, logFieldChanges, getTicketLogs, ACTION_TYPES } = require('../../../lib/logger');

async function handler(req, res) {
  const { id } = req.query;

  if (!id || isNaN(parseInt(id))) {
    return res.status(400).json({
      success: false,
      message: '无效的工单ID'
    });
  }

  try {
    switch (req.method) {
      case 'GET':
        return await getTicketById(req, res, parseInt(id));
      case 'PUT':
        return await updateTicket(req, res, parseInt(id));
      case 'DELETE':
        return await deleteTicket(req, res, parseInt(id));
      default:
        return res.status(405).json({
          success: false,
          message: '方法不允许'
        });
    }
  } catch (error) {
    console.error('工单详情API错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
}

// 获取工单详情
async function getTicketById(req, res, ticketId) {
  // 检查权限
  const hasPermission = await checkTicketPermission(req.user, ticketId, 'read');
  if (!hasPermission) {
    return res.status(403).json({
      success: false,
      message: '无权限访问此工单'
    });
  }

  try {
    // 获取工单基本信息
    const ticketSql = `
      SELECT 
        t.*,
        u.name as user_name,
        u.department as user_department,
        u.email as user_email,
        u.employee_id as user_employee_id,
        s.name as support_staff_name,
        s.department as support_department,
        s.email as support_staff_email,
        s.employee_id as support_employee_id,
        vr.name as verification_requested_by_name,
        v.name as verified_by_name,
        lm.name as last_modified_by_name,
        app.name as application_name,
        app.code as application_code,
        mod.name as module_name,
        mod.code as module_code,
        pc.name as product_category_name,
        pc.code as product_category_code,
        rt.title as resolution_template_title,
        GROUP_CONCAT(DISTINCT tag.name ORDER BY tag.name) as tag_names,
        GROUP_CONCAT(DISTINCT tag.color ORDER BY tag.name) as tag_colors
      FROM tickets t
      LEFT JOIN users u ON t.user_id = u.id
      LEFT JOIN users s ON t.support_staff_id = s.id
      LEFT JOIN users vr ON t.verification_requested_by = vr.id
      LEFT JOIN users v ON t.verified_by = v.id
      LEFT JOIN users lm ON t.last_modified_by = lm.id
      LEFT JOIN applications app ON t.application_id = app.id
      LEFT JOIN modules mod ON t.module_id = mod.id
      LEFT JOIN product_categories pc ON t.product_category_id = pc.id
      LEFT JOIN solution_templates rt ON t.resolution_template_id = rt.id
      LEFT JOIN ticket_tags tt ON t.id = tt.ticket_id
      LEFT JOIN tags tag ON tt.tag_id = tag.id
      WHERE t.id = ?
      GROUP BY t.id
    `;

    const ticketResult = await query(ticketSql, [ticketId]);
    
    if (ticketResult.length === 0) {
      return res.status(404).json({
        success: false,
        message: '工单不存在'
      });
    }

    const ticket = ticketResult[0];

    // 并行获取相关数据
    const [comments, internalNotes, logs, permissions] = await Promise.all([
      // 获取公开评论
      query(`
        SELECT 
          tc.*,
          u.name as user_name,
          u.department as user_department
        FROM ticket_comments tc
        LEFT JOIN users u ON tc.user_id = u.id
        WHERE tc.ticket_id = ?
        ORDER BY tc.created_at ASC
      `, [ticketId]),

      // 获取内部备注（根据权限过滤）
      getInternalNotes(req.user, ticketId),

      // 获取操作日志
      getTicketLogs(ticketId, 50, 0),

      // 获取用户权限
      getUserTicketPermissions(req.user.id, ticketId)
    ]);

    // 处理标签数据
    if (ticket.tag_names) {
      ticket.tags = ticket.tag_names.split(',').map((name, index) => ({
        name: name,
        color: ticket.tag_colors.split(',')[index] || '#007bff'
      }));
    } else {
      ticket.tags = [];
    }

    // 清理不需要的字段
    delete ticket.tag_names;
    delete ticket.tag_colors;

    res.status(200).json({
      success: true,
      data: {
        ticket,
        comments,
        internalNotes,
        logs,
        permissions,
        canEdit: await checkTicketPermission(req.user, ticketId, 'write'),
        canVerify: await checkTicketPermission(req.user, ticketId, 'verify'),
        canAdmin: await checkTicketPermission(req.user, ticketId, 'admin')
      }
    });
  } catch (error) {
    console.error('获取工单详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取工单详情失败'
    });
  }
}

// 更新工单
async function updateTicket(req, res, ticketId) {
  // 检查权限
  const hasPermission = await checkTicketPermission(req.user, ticketId, 'write');
  if (!hasPermission) {
    return res.status(403).json({
      success: false,
      message: '无权限修改此工单'
    });
  }

  // 验证请求数据
  const validation = validate(ticketUpdateSchema, req.body);
  if (!validation.isValid) {
    return res.status(400).json({
      success: false,
      message: '请求数据验证失败',
      errors: validation.errors
    });
  }

  const updateData = validation.data;

  try {
    await transaction(async (connection) => {
      // 获取当前工单信息
      const currentTicket = await query('SELECT * FROM tickets WHERE id = ?', [ticketId]);
      if (currentTicket.length === 0) {
        throw new Error('工单不存在');
      }

      const oldTicket = currentTicket[0];

      // 检查状态流转权限
      if (updateData.status && updateData.status !== oldTicket.status) {
        const canTransition = await checkStatusTransition(req.user, oldTicket.status, updateData.status);
        if (!canTransition.allowed) {
          throw new Error(canTransition.message);
        }
        
        // 如果需要验证，设置验证状态
        if (canTransition.requiresVerification) {
          updateData.verification_status = 'pending';
          updateData.verification_requested_by = req.user.id;
          updateData.verification_requested_at = new Date();
        }
      }

      // 设置最后修改人
      updateData.last_modified_by = req.user.id;

      // 构建更新SQL
      const updateFields = [];
      const updateValues = [];
      
      Object.keys(updateData).forEach(key => {
        if (updateData[key] !== undefined) {
          updateFields.push(`${key} = ?`);
          updateValues.push(updateData[key]);
        }
      });

      // 如果状态更新为已解决，记录解决时间
      if (updateData.status === 'resolved' && oldTicket.status !== 'resolved') {
        updateFields.push('resolved_at = CURRENT_TIMESTAMP');
      }

      // 如果状态更新为已关闭，记录关闭时间
      if (updateData.status === 'closed' && oldTicket.status !== 'closed') {
        updateFields.push('closed_at = CURRENT_TIMESTAMP');
      }

      if (updateFields.length === 0) {
        throw new Error('没有需要更新的数据');
      }

      updateValues.push(ticketId);

      const updateSql = `
        UPDATE tickets 
        SET ${updateFields.join(', ')}, updated_at = CURRENT_TIMESTAMP
        WHERE id = ?
      `;

      await query(updateSql, updateValues);

      // 处理标签更新
      if (updateData.tags && Array.isArray(updateData.tags)) {
        await updateTicketTags(ticketId, updateData.tags);
      }

      // 收集变更信息并记录详细日志
      const changes = {};
      Object.keys(updateData).forEach(key => {
        if (updateData[key] !== undefined && updateData[key] !== oldTicket[key]) {
          changes[key] = {
            old: oldTicket[key],
            new: updateData[key]
          };
        }
      });

      if (Object.keys(changes).length > 0) {
        await logFieldChanges(
          ticketId,
          req.user.id,
          changes,
          req.headers['x-forwarded-for'] || req.connection.remoteAddress,
          req.headers['user-agent']
        );
      }
    });

    // 获取更新后的工单信息
    const updatedTicket = await query(`
      SELECT 
        t.*,
        u.name as user_name,
        s.name as support_staff_name
      FROM tickets t
      LEFT JOIN users u ON t.user_id = u.id
      LEFT JOIN users s ON t.support_staff_id = s.id
      WHERE t.id = ?
    `, [ticketId]);

    res.status(200).json({
      success: true,
      message: '工单更新成功',
      data: updatedTicket[0]
    });
  } catch (error) {
    console.error('更新工单失败:', error);
    res.status(500).json({
      success: false,
      message: error.message || '更新工单失败'
    });
  }
}

// 删除工单（软删除或权限控制）
async function deleteTicket(req, res, ticketId) {
  // 只有管理员可以删除工单
  if (req.user.role !== 'administrator') {
    return res.status(403).json({
      success: false,
      message: '无权限删除工单'
    });
  }

  try {
    // 记录删除操作
    await logTicketAction({
      ticketId,
      userId: req.user.id,
      actionType: ACTION_TYPES.CANCELLED,
      description: '工单已被管理员删除',
      ipAddress: req.headers['x-forwarded-for'] || req.connection.remoteAddress,
      userAgent: req.headers['user-agent']
    });

    // 软删除：更新状态为cancelled
    await query(
      'UPDATE tickets SET status = ?, last_modified_by = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?', 
      ['cancelled', req.user.id, ticketId]
    );

    res.status(200).json({
      success: true,
      message: '工单删除成功'
    });
  } catch (error) {
    console.error('删除工单失败:', error);
    res.status(500).json({
      success: false,
      message: '删除工单失败'
    });
  }
}

// 检查工单权限
async function checkTicketPermission(user, ticketId, permissionType) {
  try {
    // 管理员拥有所有权限
    if (user.role === 'administrator') {
      return true;
    }

    // 获取工单信息
    const ticketInfo = await query(
      'SELECT user_id, support_staff_id, status FROM tickets WHERE id = ?', 
      [ticketId]
    );
    
    if (ticketInfo.length === 0) {
      return false;
    }

    const ticket = ticketInfo[0];

    // 工单创建者权限
    if (ticket.user_id === user.id) {
      switch (permissionType) {
        case 'read': return true;
        case 'write': return ['pending', 'in_progress'].includes(ticket.status);
        case 'verify': return true; // 用户可以验证支持人员的解决方案
        case 'admin': return false;
      }
    }

    // 分配的支持人员权限
    if (ticket.support_staff_id === user.id && ['support', 'operator'].includes(user.role)) {
      switch (permissionType) {
        case 'read': return true;
        case 'write': return true;
        case 'verify': return false; // 支持人员不能验证自己的工作
        case 'admin': return user.role === 'operator';
      }
    }

    // 支持角色的通用权限
    if (['support', 'operator'].includes(user.role)) {
      switch (permissionType) {
        case 'read': return true;
        case 'write': return user.role === 'operator' || ticket.support_staff_id === null;
        case 'verify': return user.role === 'operator';
        case 'admin': return user.role === 'operator';
      }
    }

    return false;
  } catch (error) {
    console.error('检查权限失败:', error);
    return false;
  }
}

// 检查状态流转权限
async function checkStatusTransition(user, fromStatus, toStatus) {
  try {
    const rules = await query(
      `SELECT * FROM ticket_status_transitions 
       WHERE from_status = ? AND to_status = ? AND required_role = ? AND is_allowed = 1`,
      [fromStatus, toStatus, user.role]
    );

    if (rules.length === 0) {
      return {
        allowed: false,
        message: `无权限将工单状态从 "${fromStatus}" 变更为 "${toStatus}"`
      };
    }

    const rule = rules[0];
    return {
      allowed: true,
      requiresVerification: rule.requires_verification,
      verificationRole: rule.verification_role,
      message: 'ok'
    };
  } catch (error) {
    console.error('检查状态流转权限失败:', error);
    return {
      allowed: false,
      message: '权限检查失败'
    };
  }
}

// 获取内部备注（根据权限过滤）
async function getInternalNotes(user, ticketId) {
  let visibilityFilter = '';
  
  if (user.role === 'user') {
    return []; // 普通用户不能查看内部备注
  } else if (user.role === 'support') {
    visibilityFilter = "AND (tin.visibility IN ('all_internal', 'support_only'))";
  } else if (user.role === 'operator') {
    visibilityFilter = "AND tin.visibility IN ('all_internal', 'support_only')";
  }
  // 管理员可以查看所有备注

  return await query(`
    SELECT 
      tin.*,
      u.name as user_name,
      u.department as user_department
    FROM ticket_internal_notes tin
    LEFT JOIN users u ON tin.user_id = u.id
    WHERE tin.ticket_id = ? ${visibilityFilter}
    ORDER BY tin.is_pinned DESC, tin.created_at DESC
  `, [ticketId]);
}

// 获取用户对工单的权限
async function getUserTicketPermissions(userId, ticketId) {
  return await query(
    `SELECT permission_type, granted_at, expires_at 
     FROM ticket_permissions 
     WHERE user_id = ? AND ticket_id = ? AND is_active = 1 
     AND (expires_at IS NULL OR expires_at > NOW())`,
    [userId, ticketId]
  );
}

// 更新工单标签
async function updateTicketTags(ticketId, tagNames) {
  // 删除现有标签关联
  await query('DELETE FROM ticket_tags WHERE ticket_id = ?', [ticketId]);

  // 添加新标签
  for (const tagName of tagNames) {
    if (!tagName || tagName.trim() === '') continue;
    
    const trimmedTagName = tagName.trim();
    
    // 查找或创建标签
    let tag = await query('SELECT id FROM tags WHERE name = ?', [trimmedTagName]);
    
    if (tag.length === 0) {
      const insertTagResult = await query(
        'INSERT INTO tags (name, color) VALUES (?, ?)',
        [trimmedTagName, '#007bff']
      );
      tag = [{ id: insertTagResult.insertId }];
    }
    
    // 创建工单标签关联
    await query(
      'INSERT IGNORE INTO ticket_tags (ticket_id, tag_id) VALUES (?, ?)',
      [ticketId, tag[0].id]
    );
  }
}


export default authenticateToken(handler);